/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package input;

import java.io.File;
import java.util.Vector;

import javax.swing.JFileChooser;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import GUI.BaseFrame;

/**
 * 
 * @author Bunkowski
 */
public class JxlExporter {

	private static void exportXLS(Vector<String[]> content, File file) {
		try {
			WritableWorkbook workbook = Workbook.createWorkbook(file);

			WritableSheet sheet = workbook.createSheet("Sheet", 0);
			for (int i = 0; i < content.size(); i++) {
				String[] strings = content.elementAt(i);
				for (int j = 0; j < strings.length; j++) {
					String string = strings[j];
					Label label = new Label(j, i, string);
					sheet.addCell(label);
				}
			}
			workbook.write();
			workbook.close();
		} catch (Exception ex) {
		}
	}

	private static void exportXLS(javax.swing.JTable table, java.io.File file) {
		Vector<String[]> v = new Vector<String[]>();

		String[] head = new String[table.getTableHeader().getColumnModel().getColumnCount()];
		for (int i = 0; i < head.length; i++) {
			head[i] = table.getTableHeader().getColumnModel().getColumn(i).getHeaderValue().toString();
		}
		v.add(head);

		int rows = table.getModel().getRowCount();
		int clms = table.getModel().getColumnCount();

		for (int i = 0; i < rows; i++) {
			String[] s = new String[clms];
			for (int j = 0; j < clms; j++) {
				s[j] = (String) table.getModel().getValueAt(i, j);
			}
			v.add(s);
		}
		exportXLS(v, file);
	}

	public static void exportXLS(javax.swing.JTable table) {
		JFileChooser chooser = new JFileChooser(BaseFrame.getSelectedFileTreeFile());
		chooser.setDialogType(JFileChooser.SAVE_DIALOG);
		int returnVal = chooser.showOpenDialog(null);
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			java.io.File file = chooser.getSelectedFile();
			if (!file.toString().endsWith(".xls")) {
				file = new java.io.File(file.getPath() + ".xls");
			}
			exportXLS(table, file);
		}

	}
}
